import { getMusicURL, getMusicLyric } from '@/api/music.js'
import { setItem, getItem } from '@/utils/storage'
import { Toast } from 'vant'

const state = {
  isShowPlay: false, // 显示播放页面
  audio: null,
  audioSrc: getItem('NETEASE_MUSICSRC') || 'http://',
  paused: true,
  lyric: getItem('NETEASE_LYRIC') || [] // 歌词
}

const mutations = {
  changeShowPlay (state, payload) {
    state.isShowPlay = payload
  },
  loadAudio (state, payload) {
    state.audio = payload
  },
  getAudioSrc (state, payload) {
    state.audioSrc = payload
    setItem('NETEASE_MUSICSRC', payload)
  },
  loadPaused (state, payload) {
    state.paused = payload
  },
  loadLyric (state, payload) {
    state.lyric = payload
    setItem('NETEASE_LYRIC', payload)
  }
}

const actions = {
  getMusicSrc (context, mid) {
    load(mid)
    async function load (id) {
      // 获取音乐URL
      const { data: res } = await getMusicURL(id)
      if (res[0].url) {
        await context.commit('getAudioSrc', res[0].url)
        // 获取歌词
        const { lrc: lyricRes } = await getMusicLyric(id)
        context.commit('loadLyric', lyricRes.lyric.split('\n'))
      } else {
        Toast('歌曲丢失！')
        load(
          context.rootGetters.playMusicList[
            context.rootGetters.playMusicIndex + 1
          ].mid
        )
        const index = context.rootGetters.playMusicList.findIndex(item => {
          return item.mid === res[0].id
        })
        context.commit('music/loadPlayMusicIndex', index + 1, { root: true })
      }
      context.state.audio.play()
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
